<template>
  <view class="qualificationItem">
    <view class="title">
      <text>{{ name }}</text>
      <text class="keyPoint" @click.stop="downloadTemplate" v-if="template">(下载模板)</text>
    </view>

    <view class="mainImage">
      <view class="img" @click="clickUploadImg">
        <image :src="mainImage" v-if="mainImage"></image>
        <uni-icons type="camera" size="25" color="white" class="icons"></uni-icons>
      </view>
      <view class="status" :style="this.applyStatus === 'APPLY' ? 'background:#ef231b' : ''">
        {{ matchingStatus() }}
      </view>
    </view>

    <view class="example">
      <view class="tip">{{ tip }}</view>
      <view class="exampleList">
        <view v-for="i in exampleList" class="item">
          <image :src="i.image"></image>
          <view class="icon icon1" v-if="i.example">√</view>
          <view class="icon icon2" v-else>x</view>
        </view>
      </view>
    </view>

    <view class="config" v-if="config.length">
      <uni-forms ref="baseForm" label-width="80px" border>
        <view v-for="(item, j) in config" :key="j">
          <uni-forms-item
            :label="item.title"
            :required="item.required"
            v-if="item.value.value !== true"
          >
            <uni-easyinput
              v-model="item.value"
              autoHeight
              v-if="item.control === 'input'"
              :inputBorder="false"
              :clearable="false"
              :placeholder="`请输入${item.title}`"
            />

            <uni-easyinput
              v-model="item.value"
              type="textarea"
              autoHeight
              :clearable="false"
              :inputBorder="false"
              v-if="item.control === 'textarea'"
              :placeholder="`请输入${item.title}`"
            />

            <view v-if="item.control === 'date'">
              <uni-data-checkbox
                v-model="item.value.type"
                v-if="item.name === 'expirationDate'"
                :localdata="[
                  { text: item.brotherTitle, value: 'radio' },
                  { text: item.brotherLabel, value: 'date' }
                ]"
                @change="checkboxChange(item)"
              />
              <picker
                mode="date"
                v-model="item.value.value"
                fields="day"
                class="picker"
                @change="bindDateChange($event, item)"
                v-if="item.name !== 'expirationDate'"
                placeholder="请选择日期"
              >
                {{ item.value.value }}
              </picker>
            </view>

            <view v-if="item.meta && item.meta.type === 'region'">
              <picker
                mode="multiSelector"
                :range="region"
                range-key="name"
                :value="regionValue"
                placeholder="请选择"
                v-if="item.name === 'province'"
                class="picker"
                @change="bindRegionChangeRegion"
                @columnchange="pickerColumnchangeRegion"
              >
                {{ item.regionValue }}
              </picker>
              <picker
                mode="multiSelector"
                :range="region"
                range-key="name"
                :value="regionValue"
                placeholder="请选择"
                v-if="item.name === 'city'"
                class="picker"
                @change="bindRegionChangeRegion"
                @columnchange="pickerColumnchangeRegion"
              >
                {{ item.regionValue }}
              </picker>
              <picker
                mode="multiSelector"
                :range="region"
                range-key="name"
                :value="regionValue"
                placeholder="请选择"
                v-if="item.name === 'county'"
                class="picker"
                @change="bindRegionChangeRegion"
                @columnchange="pickerColumnchangeRegion"
              >
                {{ item.regionValue }}
              </picker>
            </view>

            <picker
              mode="selector"
              :range="option"
              range-key="value"
              :value="optionValue"
              placeholder="请选择"
              v-if="item.meta && item.meta.type === 'select'"
              class="picker"
              @change="bindRegionChangeSelector($event, item)"
            >
              {{ item.value }}
            </picker>
          </uni-forms-item>
        </view>
      </uni-forms>
    </view>

    <button
      class="register_button"
      @click="submitForm"
      v-if="applyStatus === 'APPLY' || applyStatus === 'UPLOADED'"
    >
      提交
    </button>

    <!-- 提交确认 弹窗 -->
    <Dialog
      :dialog="dialogVisible"
      title="温馨提示"
      content="清晰无误的材料可快速审核，您确认提交吗？"
      @confirm="dialogConfirm"
      @cancel="dialogVisible = false"
    >
    </Dialog>
    <PermissionPopup
      v-if="isPermission"
      :visible="isPermission"
      :messageTxt="permissionTxt"
      @updateVisible="isPermission = $event"
      @scanCoding="whetherUploadImg"
    >
    </PermissionPopup>
  </view>
</template>

<script>
import Dialog from '@/components/dialog'

// #ifndef MP
import { anyShareFile } from '@/utils/file-share.js'
// #endif

import {
  getClassificationConfig,
  getRegion,
  getRegionItem,
  preserveClassification,
  uploadImage,
  getIdentify
} from '@/api/reg/index'

import PermissionPopup from '@/components/permission/index.vue'

export default {
  components: {
    Dialog,
    PermissionPopup
  },
  data() {
    return {
      isPermission: false,
      permissionTxt: '',
      type: '',
      purchaserId: '',
      name: '',
      applyStatus: '',
      mainImage: '',
      imageIds: [],
      template: '',
      tip: '拍摄时确保证件边框完整，字迹清晰，亮度均匀；',
      exampleList: [],
      config: [],
      mIndex: 0,
      region: [[], [], []],
      province: '',
      city: '',
      county: '',
      provinceValue: '',
      cityValue: '',
      countyValue: '',
      regionValue: [0, 0, 0],
      option: [],
      optionValue: 0,
      dialogVisible: false
    }
  },
  onLoad(e) {
    this.type = e.type
    this.purchaserId = e.purchaserId
    this.name = e.name
    this.getList()
  },
  methods: {
    dialogConfirm() {
      let a = JSON.parse(JSON.stringify(this.config))
      let b = {}
      a.forEach((i, j) => {
        if (i.name === 'temporary') {
          a[j - 1].value.value = i.value.value
        } else {
          b[i.name] = i.value
        }
      })
      preserveClassification(this.purchaserId, this.type, {
        value: JSON.stringify(b),
        filePath: this.mainImage,
        imageIds: this.imageIds
      })
        .then(res => {
          if (res.code === 200) {
            uni.navigateBack()
          }
          uni.showToast({ icon: 'none', title: res.data, mask: true })
        })
        .finally(() => {
          this.dialogVisible = false
        })
    },
    submitForm() {
      if (!this.mainImage) {
        uni.showToast({
          icon: 'none',
          title: '请上传图片',
          mask: true
        })
        return
      }
      let a = true
      try {
        this.config.forEach(i => {
          if (i.name !== 'temporary') {
            if (typeof i.value === 'string') {
              if (!i.value) throw new Error('')
            }
            if (typeof i.value === 'object') {
              if (!i.value.value) throw new Error('')
            }
          }
        })
      } catch (e) {
        a = false
      }

      if (a) {
        this.dialogVisible = true
      } else {
        uni.showToast({
          icon: 'none',
          title: '请输入必填项',
          mask: true
        })
      }
    },
    bindRegionChangeSelector(e, item) {
      this.option.forEach((i, j) => {
        if (e.detail.value == j) {
          this.optionValue = j
          item.value = i.value
        }
      })
    },
    pickerColumnchangeRegion(e) {
      if (e.detail.column === 0) {
        this.region[0].forEach((i, m) => {
          if (e.detail.value === m) {
            // 给省赋值 下标
            this.province = i.id
            this.provinceValue = i.name
            this.regionValue[0] = m
            // 市的数组 下标
            this.region[1] = i.children
            this.regionValue[1] = 0
            // 给市赋值
            this.city = this.region[1][0].id
            this.cityValue = this.region[1][0].name
            // 区的数组 下标
            this.region[2] = []
            this.regionValue[2] = 0
            // 给区赋值
            this.county = ''
            this.countyValue = ''
            // 获取区的数据
            this.selectCity()
          }
        })
      }
      if (e.detail.column === 1) {
        this.region[1].forEach((i, m) => {
          if (e.detail.value === m) {
            // 给市赋值
            this.city = i.id
            this.cityValue = i.name
            this.regionValue[1] = m
            // 区的数组 下标
            this.region[2] = []
            this.regionValue[2] = 0
            // 给区赋值
            this.county = ''
            this.countyValue = ''
            // 获取区的数据
            this.selectCity()
          }
        })
      }
      if (e.detail.column === 2) {
        this.region[2].forEach((i, j) => {
          if (e.detail.value === j) {
            // 给区赋值
            this.county = i.id
            this.countyValue = i.name
            this.regionValue[2] = j
            this.matchingConfig()
          }
        })
      }
    },
    bindRegionChangeRegion(e) {},
    checkboxChange(e) {
      if (e.value.type === 'radio') {
        this.config[this.mIndex + 1].value.type = 'radio'
        this.config[this.mIndex + 1].value.value = true
      }
      if (e.value.type === 'date') {
        this.config[this.mIndex + 1].value.type = 'date'
        this.config[this.mIndex + 1].value.value = this.currentTime()
      }
    },
    bindDateChange(e, item) {
      item.value.value = e.detail.value
    },
    matchingStatus() {
      if (this.mainImage) {
        if (
          this.applyStatus === 'APPLY' ||
          this.applyStatus === 'PASS' ||
          this.applyStatus === 'WAIT_AUDIT' ||
          this.applyStatus === 'UPLOADED'
        ) {
          return '已填写'
        }
      }
      return '待补充'
    },
    getList() {
      let temporary_arr = []
      getClassificationConfig(this.purchaserId, this.type).then(res => {
        if (res.code === 200) {
          this.applyStatus = res.data.applyStatus
          this.mainImage = res.data.filePath
          this.template = res.data.template
          this.tip = res.data.tip
          this.imageIds = res.data.imageIds
          res.data.correctExample.split(',').forEach(i => {
            this.exampleList.push({
              example: true,
              image: i
            })
          })
          res.data.unsuitableExamples.split(',').forEach(i => {
            this.exampleList.push({
              example: false,
              image: i
            })
          })
          if (res.data.config) {
            let a = JSON.parse(res.data.config.replace('\\', ''))
            for (const key in a) {
              this.$set(a[key], 'name', key)
              if (!a[key].value) {
                if (a[key].control === 'date') {
                  this.$set(a[key], 'value', {
                    type: 'date',
                    value: this.currentTime()
                  })
                } else {
                  this.$set(a[key], 'value', '')
                }
              }
              this.config.push(a[key])
              if (a[key].control === 'select' && a[key].meta.type === 'select') {
                this.option = a[key].meta.list
                if (!a[key].value) a[key].value = this.option[0].value
                this.option.forEach((i, j) => {
                  if (i.value === a[key].value) this.optionValue = j
                })
              }
              if (a[key].control === 'select' && a[key].meta.type === 'region')
                temporary_arr.push(a[key])
            }

            temporary_arr.forEach((i, j) => {
              if (i.name === 'province') {
                this.province = i.value
              }
              if (i.name === 'city') {
                this.city = i.value
              }
              if (i.name === 'county') {
                this.county = i.value
              }
              if (temporary_arr.length === j + 1) {
                getRegion().then(res => {
                  this.region[0] = res.data
                  this.region[1] = []
                  this.region[2] = []
                  this.regionValue[0] = 0
                  if (!this.province) this.province = this.region[0][0].id
                  this.region[0].forEach((i, m) => {
                    if (i.id === this.province) {
                      this.provinceValue = i.name
                      this.regionValue[0] = m
                      this.region[1] = i.children
                      if (!this.city) this.city = this.region[1][0].id
                      i.children.forEach((j, k) => {
                        if (j.id === this.city) {
                          this.cityValue = j.name
                          this.regionValue[1] = k
                        }
                      })
                    }
                  })
                  this.selectCity()
                })
              }
            })
            this.config = this.config.sort(function (a, b) {
              return a['sortNum'] - b['sortNum']
            })

            this.config.forEach((i, j) => {
              if (i.name === 'expirationDate') {
                this.mIndex = j
              }
            })
            if (this.mIndex) {
              let value = {
                type: this.config[this.mIndex].value.type,
                value:
                  JSON.parse(JSON.stringify(this.config[this.mIndex].value.value)) ||
                  this.currentTime()
              }
              this.config.splice(this.mIndex + 1, 0, {
                control: 'date',
                name: 'temporary',
                title: '具体日期',
                value: value
              })
            }
          }
        }
      })
    },
    matchingConfig() {
      this.config.forEach(i => {
        if (i.name === 'province') {
          i.regionValue = this.provinceValue
          i.value = this.province
        }
        if (i.name === 'city') {
          i.regionValue = this.cityValue
          i.value = this.city
        }
        if (i.name === 'county') {
          i.regionValue = this.countyValue
          i.value = this.county
        }
      })
      this.$forceUpdate()
    },
    selectCity() {
      let that = this
      let timeId = 0
      clearTimeout(timeId)
      timeId = setTimeout(function () {
        getRegionItem(that.city).then(res => {
          if (res.code === 200) {
            if (that.county) {
              res.data.forEach((i, j) => {
                if (that.county === i.id) {
                  that.countyValue = i.name
                  that.regionValue[2] = j
                }
              })
            } else {
              that.county = res.data[0].id
              that.countyValue = res.data[0].name
              that.regionValue[2] = 0
            }
            that.region[2] = res.data
            that.matchingConfig()
          }
        })
      }, 500)
    },
    // 注册 上传资质图片
    clickUploadImg() {
      // #ifndef MP
      if (uni.getSystemInfoSync().osName === 'ios') {
        this.whetherUploadImg()
      } else {
        this.isPermission = true
        this.permissionTxt =
          '用于获取设备权限进行拍照、图片上传，需要获取手机相机、相册（存储）权限'
      }
      // #endif
      // #ifdef MP
      this.whetherUploadImg()
      // #endif
    },
    whetherUploadImg() {
      let that = this
      uni.chooseImage({
        success(res) {
          if (res.tempFiles[0].size / 1024 / 1024 > 5) {
            uni.showToast({
              icon: 'none',
              title: '上传的图片不能大于5Mb',
              mask: true
            })
            return
          }

          uni.uploadFile({
            url: 'https://www.xdyy100.com/wholesale/essential/common/common/upload/file', //上传图片api
            name: 'file',
            filePath: res.tempFiles[0].path,
            formData: {
              directory: '/files/materials'
            },
            header: {
              accessToken: uni.getStorageSync('token'),
              'Content-type': 'multipart/form-data'
            },
            success: res => {
              let group = JSON.parse(res.data)
              if (group.code === 200) {
                that.mainImage = group.data.url
                that.imageIds = [group.data.id]
                getIdentify({
                  classificationId: that.type,
                  fileId: group.data.id
                }).then(res => {
                  if (res.code === 200) {
                    let receive = res.data
                    for (const key in receive) {
                      that.config.forEach(i => {
                        if (key === i.name) {
                          receive[key] ? (i.value = receive[key]) : ''
                        }
                      })
                      if (key === 'province') {
                        receive[key] ? (that.province = receive[key]) : ''
                      }
                      if (key === 'city') {
                        receive[key] ? (that.city = receive[key]) : ''
                      }
                      if (key === 'county') {
                        receive[key] ? (that.county = receive[key]) : ''
                      }
                    }
                    if (that.province) {
                      that.region[0].forEach((i, j) => {
                        if (that.province === i.id) {
                          that.region[1] = i.children
                          that.regionValue[0] = j
                        }
                      })
                    }
                    if (that.city) {
                      that.region[1].forEach((i, j) => {
                        if (that.city === i.id) {
                          that.regionValue[1] = j
                          that.selectCity()
                        }
                      })
                    }

                    that.config.forEach((i, j) => {
                      if (i.name === 'temporary') {
                        let value = {
                          type: that.config[j - 1].value.type,
                          value: that.config[j - 1].value.value || that.currentTime()
                        }
                        i.value = value
                      }
                    })
                  }
                })
              } else {
                uni.showToast({
                  icon: 'none',
                  title: group.msg,
                  mask: true
                })
              }
            }
          })
        }
      })
    },
    downloadTemplate() {
      let that = this
      uni.showLoading({ title: '正在下载...' })
      // #ifndef MP
      let shareParams = { url: that.template, name: this.name }
      anyShareFile(shareParams)
      // #endif

      // #ifdef MP
      uni.downloadFile({
        url: that.template, //仅为示例，并非真实的资源
        success: res => {
          if (res.statusCode === 200) {
            uni.hideLoading()
            wx.shareFileMessage({
              filePath: res.tempFilePath,
              success: data => {
                uni.showToast({ icon: 'success', title: '转发成功', mask: true })
              }
            })
          }
        },
        fail: () => {
          uni.showToast({ icon: 'none', title: '文件下载失败', mask: true })
        }
      })
      // #endif
    },
    currentTime() {
      let date = new Date()
      return `${date.getFullYear()}-${('0' + (date.getMonth() + 1)).slice(-2)}-${(
        '0' + date.getDate()
      ).slice(-2)}`
    }
  }
}
</script>

<style lang="scss" scoped>
.uniui-calendar {
  display: none;
}

.qualificationItem {
  padding: 25rpx;
  background: #f9f9f9;
  min-height: calc(100vh - 50rpx);

  .title,
  .mainImage,
  .example,
  .config {
    background: #fff;
    border-radius: 10rpx;
  }

  .title {
    border-radius: 10rpx 10rpx 0 0;
    padding: 48rpx 0 37.5rpx 24.31rpx;

    text {
      font-size: 35rpx;
      font-weight: 500;
    }

    .keyPoint {
      font-size: 17rpx;
      color: #ef231b;
      margin-left: 13rpx;
    }
  }

  .mainImage {
    padding-left: 18.06rpx;
    padding-bottom: 41.67rpx;
    margin-bottom: 20.83rpx;

    .img {
      width: 319rpx;
      height: 249rpx;
      background: #f9f9f9;
      border-radius: 7rpx;
      position: relative;

      image {
        width: 319rpx;
        height: 249rpx;
        display: block;
      }

      .icons {
        width: 40rpx;
        height: 40rpx;
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
        color: #fff;
        padding: 20rpx;
        background: rgba($color: #000000, $alpha: 0.4);
        border-radius: 50%;
        display: flex;
        justify-content: center;
        align-items: center;
      }
    }

    .status {
      width: 319rpx;
      height: 49rpx;
      line-height: 49rpx;
      background: #2871fc;
      border-radius: 7rpx;
      text-align: center;
      color: #ffffff;
      font-size: 29rpx;
    }
  }

  .example {
    padding: 44.44rpx 10.42rpx 0;
    margin-bottom: 20.83rpx;

    .tip {
      font-size: 25rpx;
      font-weight: 400;
      color: #261d1d;
      line-height: 1;
      margin-bottom: 35.42rpx;
      margin-left: 11.81rpx;
    }

    .exampleList {
      display: flex;
      flex-flow: row nowrap;
      justify-content: space-between;
      overflow-x: auto;

      .item {
        position: relative;
        margin-right: 20.83rpx;
        margin-bottom: 36.11rpx;

        image {
          width: 154rpx;
          height: 111rpx;
        }

        .icon {
          width: 30rpx;
          height: 30rpx;
          text-align: center;
          line-height: 26rpx;
          position: absolute;
          left: 50%;
          bottom: -10rpx;
          transform: translateX(-50%);
          border-radius: 50%;
          color: #fff;
          font-size: 30rpx;
        }

        .icon1 {
          line-height: 30rpx;
          background: #2871fc;
        }

        .icon2 {
          background: #f5422f;
        }
      }

      .item:last-child {
        margin-right: 0;
      }
    }
  }

  .config {
    padding: 41rpx 17.36rpx 0;
    margin-bottom: 250rpx;

    .picker {
      padding-left: 20rpx;
      padding-right: 20rpx;
      line-height: 70rpx;
      display: flex;
      flex-flow: row nowrap;
      justify-content: space-between;
      align-items: center;
    }

    .picker::after {
      content: '>';
      color: #585858;
    }

    ::v-deep .uni-data-checklist > .checklist-group > .checklist-box {
      margin: 0 !important;
      height: 70rpx !important;
      margin-right: 50rpx !important;
    }
  }

  .register_button {
    width: 667rpx;
    height: 72rpx;
    background: #2871fc;
    border-radius: 36rpx;
    color: #fff;
    font-size: 29rpx;
    position: fixed;
    left: 50%;
    bottom: 104rpx;
    transform: translateX(-50%);
    z-index: 10;
  }
}
</style>
